using namespace std;
#include <iostream>
#include <vector>
#include "functionsPgm.h"

void sogliatura( const unsigned char *buf, unsigned char *out,unsigned int width, unsigned int height,short treshold)
{
    for (int i=0; i<(width*height); ++i) {
        if (buf[i]<treshold) out[i]=0;
        else out[i]=255;
    }

}
void copia( const unsigned char *buf, unsigned char *out,unsigned int width, unsigned int height,short treshold)
{
    for (int i=0; i<(width*height); ++i) {
        out[i] = buf[i];
    }
}
void istogramma( const unsigned char *buf,unsigned int width, unsigned int height)
{
    //inizializzazione
    int isto[256];
    for (int i=0; i<256; i++) {
        isto[i] = 0;
    }
    //creazione istogramma
    for (int i=0; i<(width*height); ++i) {
        isto[buf[i]]++;
    }
    //output
    for (int i=0; i<256; ++i) {
        cout<<i<<".\t-> "<<isto[i]<<endl;
    }
}
void abbLum( const unsigned char *buf, unsigned char *out,unsigned int width, unsigned int height,short treshold)
{
    for (int i=0; i<(width*height); ++i) {
        if (buf[i] >= treshold) out[i] = buf[i]-treshold;
        else out[i] = buf[i];
    }
}
void subImg( const unsigned char *buf1,const unsigned char *buf2, unsigned char *out,unsigned int width, unsigned int height)
{
    for (int i=0; i<(width*height); ++i) {
       if (buf2[i]>=buf1[i]) 
		   out[i] = buf2[i]-buf1[i];
		else out[i] = buf1[i]-buf2[i];
    }
}
void filtroMed( const unsigned char *buf, unsigned char *out,unsigned int width, unsigned int height, unsigned int rayFilter)
{
  /*  int sum,j;
    for (int i=0; i<(width*height); i++) {
        sum=0;
		j=0;
        if (i-1>=0) {
            sum+=buf[i-1];
	    j++;
            if ((i-width+1)>=0) {
                sum+=buf[i-width+1];
                j++;
		if (i-width>=0) {
                    sum+=buf[i-width];
                    j++;
		    if (i-width-1>=0) {
                        sum+=buf[i-width-1];
		      j++;
		      
		    }
                }
            }
        }
        else if (i+1<width*height) {
            sum+=buf[i+1];
	    j++;
            if (i+width-1<width*height) {
                sum+=buf[i+width-1];
                j++;
		if (i+width<width*height) {
                    sum+=buf[i+width];
                    j++;
		    if (i+width+1<width*height) {
                        sum+=buf[i+width+1];
                    j++;
		      
		    }
                }
            }
            out[i] = sum / j;


        }

    }*/
	
	vector <int> dummy;

	for (int i=width+rayFilter; i<(width*height-rayFilter-width); i++) {
		
		if (i%width < (rayFilter) || i%width >= (width-rayFilter)) i++;
		
		else {
			for (int row=i/width-rayFilter; row<i/width+rayFilter; row++) {
				for (int col=i%width-rayFilter; col<i%width+rayFilter; col++) {
					dummy.push_back(buf[col+row*width]);
				}
			}
			sort(dummy.begin(),dummy.end());	
			out[i]=dummy[(rayFilter*2+1)*(rayFilter*2+1)/2];
			dummy.clear();
		}
		
			
		
	}
	
	
}